const DB = require('../core/DB')

const {
    Op
} = require('sequelize')
const article = require('../models/article')

DB.tag_article.belongsTo(DB.tag)
DB.tag.hasMany(DB.tag_article)


class TagController {
    /* ------------------------- ok 获取指定标签下的文章数目 -------------------------------*/
    async listTagDetail(ctx) {
        // 参数
        let {
            id,
            page = 1,
            size = 10,
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.tag_article.findAndCountAll({
            where: {
                tagId: id
            },
            offset: (page - 1) * size,
            limit: size,
            order: [
                ['id', 'DESC']
            ],
            include: DB.article
        })

        for (let article of rows) {
            let articleId = article.get('articleId')
            let t_a = await DB.tag_article.findAll({
                where: {
                    articleId
                },
                include: DB.tag
            })

            let arr = []
            for (let v of t_a) {
                arr.push(v.get('tag'))
            }

            article.dataValues.tags = arr
        }

        const data = {
            rows,
            meta: {
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        global.Response.success(ctx, undefined, data)
    }

    /* ------------------------- ok 获取所有标签 及其各文章数 -------------------------------*/
    async listTag(ctx) {

        let tags = await DB.tag.findAll({
            order: [
                ['sort', 'DESC']
            ]
        })

        for (let tag of tags) {
            let tagId = tag.get('id')
            let articleCount = await DB.tag_article.count({
                where: {
                    tagId
                }
            })
            tag.dataValues.articleCount = articleCount
        }

        global.Response.success(ctx, undefined, tags)
    }

}

module.exports = new TagController